package chuangyi.com.org.ViewModel;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.databinding.Bindable;
import android.databinding.ObservableArrayList;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.solidfire.gson.internal.LinkedTreeMap;

import java.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import chuangyi.com.org.DOMIHome.BR;
import chuangyi.com.org.DOMIHome.Fragments.CommonFragment;
import chuangyi.com.org.DOMIHome.HomeActivity;
import chuangyi.com.org.DOMIHome.LoadingDialog;
import chuangyi.com.org.DOMIHome.NotifyParentCheckedChanged;
import chuangyi.com.org.DOMIHome.PopupActivity;
import chuangyi.com.org.DOMIHome.R;
import chuangyi.com.org.DOMIHome.StretchListView;
import chuangyi.com.org.DOMIHome.Utils.Utils;
import chuangyi.com.org.DOMIHome.Utils.WebApi;
import chuangyi.com.org.DOMIHome.WaitActivityResult;
import chuangyi.com.org.DOMIHome.adapter.ListBindingAdapter;
import chuangyi.com.org.DOMIHome.adapter.XListAdapterInterface;
import chuangyi.com.org.DOMIHome.adapter.XListBindingAdapter;
import chuangyi.com.org.DOMIHome.databinding.CheckedMenuBinding;

/**
 * 交流模块主界面
 * Created by zxh on 16/11/29.
 */

public class CommunicationModel extends XListModel implements WaitActivityResult, NotifyParentCheckedChanged {
    /**
     * 跳转到完善资料页
     */
    public static final int GOTO_COMPLETE_INFO = 0;
    /**
     * 专家申请进度页
     */
    public static final int GOTO_PROGRESS_PAGE = 1;
    /**
     * 申请成为专家出错
     */
    public static final int APPLY_EXPERT_ERROR = -1;

    private boolean suspend = false;

    private boolean articleSelected;
    private boolean answerSelected;
    private boolean expertSelected;
    private boolean loading;
    private String buttonText;
    private RewardCheckMenu checkMenu;
    //    private int checkedMenu;
    private ArrayList expertDomain;
    private ListBindingAdapter<CheckedMenuItem> menus;
    private ListBindingAdapter sortMenu;
    private ListBindingAdapter areas;
    private String sortCode;
    private String selectedAreas;

    @Bindable
    public boolean isArticleSelected() {
        return articleSelected;
    }

    public void setArticleSelected(boolean articleSelected) {
        this.articleSelected = articleSelected;
        if (articleSelected) {
            setExpertSelected(false);
            setAnswerSelected(false);
            setButtonText("发文");
            setMenuList();
        }
        notifyPropertyChanged(BR.articleSelected);
    }

    @Bindable
    public boolean isAnswerSelected() {
        return answerSelected;
    }

    public void setAnswerSelected(boolean answerSelected) {
        this.answerSelected = answerSelected;
        if (answerSelected) {
            setArticleSelected(false);
            setExpertSelected(false);
            setButtonText("提问");
            setMenuList();
        }
        notifyPropertyChanged(BR.answerSelected);
    }

    @Bindable
    public boolean isExpertSelected() {
        return expertSelected;
    }

    public void setExpertSelected(boolean expertSelected) {
        this.expertSelected = expertSelected;
        if (expertSelected) {
            setArticleSelected(false);
            setAnswerSelected(false);
            setButtonText("申请专家");
            setMenuList();
        }
        notifyPropertyChanged(BR.expertSelected);
    }

    @Bindable
    public String getButtonText() {
        return buttonText;
    }

    public void setButtonText(String buttonText) {
        this.buttonText = buttonText;
        notifyPropertyChanged(BR.buttonText);
    }

//    @Bindable
//    public int getCheckedMenu() {
//        return checkedMenu;
//    }
//
//    public void setCheckedMenu(int checkedMenu) {
//        this.checkedMenu = checkedMenu;
//        getAdapter().clear();
//        getAdapter().notifyDataSetChanged();
//        setCurrentPage(1);
//        load(1);
//    }

    @Bindable
    public ListBindingAdapter<CheckedMenuItem> getMenus() {
        return menus;
    }

    public CommunicationModel(Context context) {
        super(context);
        List<Integer> layoutTypes = new ArrayList<Integer>();
        layoutTypes.add(R.layout.checked_menu);
        layoutTypes.add(R.layout.i_checkbox_menu);
        menus = new ListBindingAdapter<CheckedMenuItem>(getContext(), BR.menu, layoutTypes);
        this.articleSelected = true;
        this.buttonText = "发文";
        this.selectedAreas = "";
        setMenuList();
        init();
        sortCode = "";
    }

    private void setMenuList() {
        menus.clear(true);
        Context context = getContext();
        if (answerSelected) {
            CheckedMenuItem menuItem = new CheckedMenuItem(context, R.layout.checked_menu, "全部", "all");
            menuItem.setChecked(true);
            menuItem.setParent(this);
            menus.add(menuItem);

            checkMenu = new RewardCheckMenu(context, R.layout.i_checked_menu_reward);
            checkMenu.setCode("xs");
            checkMenu.setTitle("悬赏");
            checkMenu.setParent(this);
            menus.add(checkMenu);

            menuItem = new CheckedMenuItem(context, R.layout.checked_menu, "问题", "tw");
            menuItem.setParent(this);
            menus.add(menuItem);
            sortCode = "";
        } else if (expertSelected) {
            if (expertDomain != null) {
                ArrayList<String> selected = new ArrayList<String>();
                for (Object item : expertDomain) {
                    LinkedTreeMap map = (LinkedTreeMap) item;
                    CheckedMenuItem menuItem = new CheckedMenuItem(getContext(), R.layout.i_checked_menu);
                    menuItem.setTitle((String) map.get("param1"));
                    menuItem.setChecked(selected.contains(menuItem.getTitle()));
                    menuItem.setParent(this);
                    menus.add(menuItem);
                }
            }
            sortCode = "";
        }
        menus.notifyDataSetChanged();
    }

    public void onClickArticle(View view) {
        getAdapter().clear(true);
        setArticleSelected(true);
        setCurrentPage(1);
        load(1);
    }

    public void onClickAnswer(View view) {
        getAdapter().clear(true);
        setAnswerSelected(true);
        setCurrentPage(1);
        load(1);
    }

    public void onClickExpert(View view) {
        getAdapter().clear(true);
        setExpertSelected(true);
        setCurrentPage(1);
        load(1);
    }

    /**
     * 点击按钮
     *
     * @param View
     */
    public void onClickButton(View View) {
        if (expertSelected) {
            // 开始申请专家流程
            HomeActivity.beginApplyExpert(getContext());
            return;
        }
        LoadingDialog.getInstance(getContext()).show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (WebApi.allowAction(getContext())) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (articleSelected) {
                                // 打开发文章界面
                                ArticleEditModel editor = new ArticleEditModel(getContext());

                                final CommonFragment fragment = new CommonFragment();
                                fragment.setLayoutId(R.layout.f_send_article);
                                fragment.setVariableId(BR.editor);
                                fragment.setDataModel(editor);
                                HomeActivity.switchFragment((Activity) getContext(), fragment);
                            } else if (answerSelected) {
                                // 打开发布悬赏
                                EditReward reward = new EditReward(getContext());

                                CommonFragment fragment = new CommonFragment();
                                fragment.setLayoutId(R.layout.f_send_xuanshang);
                                fragment.setVariableId(BR.editor);
                                fragment.setDataModel(reward);
                                HomeActivity.switchFragment((Activity) getContext(), fragment);
                            }
                        }
                    });
                }
                LoadingDialog.getInstance(getContext()).dismiss();
            }
        }).start();

    }

    private void init() {
        List<Integer> viewTypeList = new ArrayList<Integer>();
        viewTypeList.add(R.layout.i_advice);
        viewTypeList.add(R.layout.i_question);
        viewTypeList.add(R.layout.i_article);
        getAdapter().setViewType(viewTypeList);
        new Thread(new Runnable() {
            @Override
            public void run() {
                expertDomain = WebApi.getExpertDomainList(getContext());
                if (expertSelected) {
                    int index = 0;
                    for (Object item : expertDomain) {
                        LinkedTreeMap map = (LinkedTreeMap) item;
                        CheckedMenuItem menuItem = new CheckedMenuItem(getContext(), R.layout.i_checkbox_menu);
                        menuItem.setTitle((String) map.get("param1"));
                        menuItem.setChecked(false);
                        menuItem.setParent(CommunicationModel.this);
                        menus.add(menuItem);
                        index++;
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            notifyPropertyChanged(BR.menus);
                        }
                    });
                }
            }
        }).start();
    }

    @Override
    public void load(final int page) {
        if (loading)
            return;
        loading = true;
        MenuItem checkedMenuItem = null;
        if (answerSelected) {
            for (int i = 0; i < menus.getCount(); i++) {
                CheckedMenuItem menu = menus.getItem(i);
                if (menu.isChecked()) {
                    checkedMenuItem = menu;
                    break;
                }
            }
            if (checkedMenuItem == null) {
                loading = false;
                return;
            }
        }
        load(checkedMenuItem, page);
    }

    private void load(final MenuItem menuItem, final int page) {
        LoadingDialog.getInstance(getContext()).show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                ArrayList list = null;
                if (expertSelected) {
                    list = loadExpert(getContext(), sortCode, page);
                } else if (articleSelected) {
                    list = loadArticle(getContext(), page);
                } else {
                    list = loadAnswers(getContext(), menuItem, sortCode, page);
                }
                final ArrayList result = list;
                notifyDataSetChanged(result);
                LoadingDialog.getInstance(getContext()).dismiss();
                loading = false;
            }
        }).start();
    }

    /**
     * 加载文章列表
     *
     * @param context
     * @param page
     */
    private ArrayList loadArticle(final Context context, final int page) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                setHaveMore();
            }
        });
        ArrayList list = WebApi.getArticleList(getContext(), page);
        final XListAdapterInterface adapter = this.getAdapter();
        adapter.setVariableId(BR.article);
        try {
            for (Object article : list) {
                LinkedTreeMap map = (LinkedTreeMap) article;
                ArticleItem item = new ArticleItem(context, R.layout.i_article);
                item.setAvatar((String) map.get("avatar"));
                item.setAuthor((String) map.get("nickname"));
                item.setTitle((String) map.get("title"));
                item.setArticleId(Utils.getIntValue(map.get("articleid")));
                item.setSystime((String) map.get("systime"));
                item.setReplycoun(Utils.getIntValue(map.get("commentcount")));
                item.setLikecoun(Utils.getIntValue(map.get("doclikecount")));
                item.setTag((String) map.get("job"));
                item.setLabel((String) map.get("label"));
                item.setUid(Utils.getIntValue(map.get("uid")));
                ArrayList content = (ArrayList) map.get("content");

                item.setDescription(content.size() > 0 ? (String) ((LinkedTreeMap) content.get(0)).get("content") : "");
                // 图片列表
                ArrayList imageList = (ArrayList) map.get("contentimg");
                ListBindingAdapter images = item.getImageList();
                images.setVariableId(BR.src);
                for (Object image : imageList) {
                    LinkedTreeMap treeMap = (LinkedTreeMap) image;
                    ImageItem imageItem = new ImageItem(getContext());
                    imageItem.setSrc((String) treeMap.get("content"));
                    images.add(imageItem);
                    if (images.getCount() > 5) {
                        break;
                    }
                }

                adapter.add(item);
            }
            setXListMargin(true);
        } catch (Exception ex) {
            showToast("解析数据时发生错误");
            return list;
        }
        if (list.size() != 0) {
            setCurrentPage(page);
        }
        return list;
    }

    /**
     * 获取提问/回答列表
     *
     * @param context
     * @param page
     */
    private ArrayList loadAnswers(final Context context, final MenuItem checkedMenu, String sort, final int page) {
        LinkedTreeMap result = WebApi.getQuestionList(getContext(), checkedMenu.getCode(), sort, page);

        final XListAdapterInterface adapter = this.getAdapter();

        if (result == null) {
            return new ArrayList();
        }

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                adapter.clear(true);
                setNoMore();
            }
        });
        if (checkMenu != null) {
            double value = Utils.getDoubleValue(result.get("sumprice"));
            checkMenu.setValue(String.format(Locale.CHINESE, "%.1f万元", value / 10000));
        }
        ArrayList list = (ArrayList) result.get("list");
        if (list == null) {
            return new ArrayList();
        }
        adapter.setVariableId(BR.question);
        List<Integer> rankImageRes = new ArrayList<Integer>();
        rankImageRes.add(R.mipmap.rank1);
        rankImageRes.add(R.mipmap.rank2);
        rankImageRes.add(R.mipmap.rank3);
        rankImageRes.add(R.mipmap.rank4);
        rankImageRes.add(R.mipmap.rank5);

        try {
            for (Object question : list) {
                LinkedTreeMap map = (LinkedTreeMap) question;
                QuestionItem item = new QuestionItem(context, R.layout.i_question);
                ArrayList innerContent = (ArrayList) map.get("content");
                if (innerContent != null && innerContent.size() > 0) {
                    LinkedTreeMap content = (LinkedTreeMap) innerContent.get(0);
                    item.setDesc((String) content.get("content"));
                }
                item.setTitle((String) map.get("title"));
                item.setNickname((String) map.get("nickname"));
                item.setAvatar((String) map.get("avatar"));
                item.setJob((String) map.get("job"));
                item.setLabel((String) map.get("label"));
                item.setSystime((String) map.get("systime"));
//                item.setDesc((String) map.get("questiondesc"));
                item.setLefttime(Utils.getIntValue(map.get("lefttime")));
                int status = Utils.getIntValue(map.get("status"));
                switch (status) {
                    case 0:
                        item.setLefttime(-1);
                        break;
                    case 2:
                        item.setLefttime(0);
                        break;
                }
                item.setStartdate(Utils.getDateFromFormat(map.get("startdate"), "yyyy-MM-dd HH:mm:ss"));
                item.setBrowser(Utils.getIntValue(map.get("browser")));
                item.setAnswercoun(Utils.getIntValue(map.get("answercoun")));
                item.setMoney(Utils.getDoubleValue(map.get("money")));
                item.setId(Utils.getIntValue(map.get("questionid")));
                item.setUid(Utils.getIntValue(map.get("uid")));
                item.startTimer();
                // 回答人员列表
                ArrayList userList = (ArrayList) map.get("users");
                ListBindingAdapter users = item.getUsers();
                users.setVariableId(BR.user);
                int index = 0;
                for (Object user : userList) {
                    LinkedTreeMap treeMap = (LinkedTreeMap) user;
                    UserItem userItem = new UserItem(getContext());
                    userItem.setAvatar((String) treeMap.get("avatar"));
                    userItem.setUid(Utils.getIntValue(treeMap.get("uid")));
                    userItem.setLikecount(Utils.getIntValue(treeMap.get("likecou")));
                    if (index < 5) {
                        userItem.setRankRes(rankImageRes.get(index));
                    }
                    index++;
                    users.add(userItem);
                }

                adapter.add(item);
            }
        } catch (Exception ex) {
            showToast("解析数据时发生错误");
            return list;
        }
        if (list.size() != 0) {
            setCurrentPage(page);
        }
        setXListMargin(false);
        return list;
    }

    /**
     * 获取专家列表
     *
     * @param context
     * @param page
     */
    private ArrayList loadExpert(final Context context, String sortCode, final int page) {
        ArrayList list = WebApi.getExpertList(getContext(), selectedAreas, sortCode, page);
        final XListAdapterInterface adapter = this.getAdapter();
        adapter.setVariableId(BR.advice);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                adapter.clear(true);
                setNoMore();
            }
        });
        try {
            for (Object question : list) {
                LinkedTreeMap map = (LinkedTreeMap) question;
                ExpertItem item = new ExpertItem(context);

                item.setNickname((String) map.get("nickname"));
                item.setAvatar((String) map.get("avatar"));
                item.setJob((String) map.get("job"));
                item.setIntroduction((String) map.get("introduction"));
                item.setUid(Utils.getIntValue(map.get("uid")));
                item.setConsultmoney(Utils.getDoubleValue(map.get("consultmoney")));
                item.setJudgerank(Utils.getIntValue(map.get("judgerank")));
                item.setLabel((String) map.get("expertdomain"));

                adapter.add(item);
            }
        } catch (Exception ex) {
            showToast("解析数据时发生错误");
            return list;
        }
        if (list.size() != 0) {
            setCurrentPage(page);
        }
        setXListMargin(false);
        return list;
    }

    private void setXListMargin(final boolean margin) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                XListAdapterInterface adapter = getAdapter();
                ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) adapter.getxListView().getLayoutParams();
                if (!margin) {
                    layoutParams.leftMargin = 0;
                    layoutParams.rightMargin = 0;
                    adapter.getxListView().setDividerHeight(0);
                } else {
                    layoutParams.rightMargin = (int) getContext().getResources().getDimension(R.dimen.page_margin);
                    layoutParams.leftMargin = (int) getContext().getResources().getDimension(R.dimen.page_margin);
                    adapter.getxListView().setDividerHeight(1);
                }
                adapter.getxListView().setLayoutParams(layoutParams);
            }
        });
    }

    public void onClickSort(View view) {
        Intent intent = new Intent(getContext(), PopupActivity.class);
        int type = -1;
        if (answerSelected) {
            intent.putExtra("layoutId", R.layout.v_dialog_ques_sort);
            type = SortModel.ASK_SORT;
        } else if (expertSelected) {
            intent.putExtra("layoutId", R.layout.v_dialog_expert_sort);
            type = SortModel.EXPERT_SORT;
        } else {
            return;
        }
        intent.putExtra("variableId", BR.all);
        ArrayList<String> selectedAreaList = new ArrayList<String>();
        if ("".equals(selectedAreas) == false && selectedAreas != null) {
            for (String area : selectedAreas.split(",")) {
                selectedAreaList.add(area);
            }
        }
        SortModel model = new SortModel(getContext(), type, sortCode, selectedAreaList);
        model.setAreaList(menus);
        PopupActivity.setDataModel(model);

        ((Activity) getContext()).startActivityForResult(intent, HomeActivity.REQUEST_SORT);
    }

    @Override
    public void notifyCheckedChanged(CheckedMenuItem menu) {
        if (menu.isChecked()) {
            for (int i = 0; i < menus.getCount(); i++) {
                CheckedMenuItem item = menus.getItem(i);
                if (item != menu) {
                    item.setChecked(false);
                }
            }
            if (expertSelected) {
                selectedAreas = menu.getTitle();
            }
            getAdapter().clear(true);
            setCurrentPage(1);
            load(menu, 1);
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == HomeActivity.REQUEST_SORT) {
                sortCode = data.getStringExtra("sort");
                if (expertSelected) {
                    selectedAreas = data.getStringExtra("selectedArea");
                }
                getAdapter().clear(true);
                setCurrentPage(1);
                load(1);
            }
        }
    }
}
